import dotenv from 'dotenv';
import { Sequelize } from 'sequelize';
import logger from './logger.js';

dotenv.config();

// 从环境变量中获取数据库配置
const {
  NODE_ENV = 'development',
  DB_STORAGE = 'database.sqlite',
  DB_DIALECT = 'sqlite',
  DB_HOST,
  DB_PORT,
  DB_USERNAME,
  DB_PASSWORD,
  DB_NAME
} = process.env;

// 数据库配置
const config = {
  development: {
    dialect: DB_DIALECT,
    storage: `./${DB_STORAGE}`,
    logging: false,
    define: {
      timestamps: true,
      underscored: true,
      paranoid: false,
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci',
    },
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
  },
  test: {
    dialect: 'sqlite',
    storage: ':memory:',
    logging: false,
  },
  production: {
    dialect: DB_DIALECT,
    host: DB_HOST,
    port: DB_PORT,
    username: DB_USERNAME,
    password: DB_PASSWORD,
    database: DB_NAME,
    logging: (msg) => logger.debug(msg),
    define: {
      timestamps: true,
      underscored: true,
      paranoid: false,
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci',
    },
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
    dialectOptions: {
      ssl: process.env.DB_SSL === 'true' ? {
        require: true,
        rejectUnauthorized: false
      } : false,
    },
  },
};

const env = NODE_ENV || 'development';
const dbConfig = config[env];

// 创建Sequelize实例
let sequelize;
if (dbConfig.use_env_variable) {
  sequelize = new Sequelize(process.env[dbConfig.use_env_variable], dbConfig);
} else {
  sequelize = new Sequelize(
    dbConfig.database || undefined,
    dbConfig.username || undefined,
    dbConfig.password || undefined,
    dbConfig
  );
}

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    logger.info('数据库连接成功');
    return true;
  } catch (error) {
    logger.error('数据库连接失败:', error);
    return false;
  }
};

// 同步数据库模型
const syncModels = async (options = {}) => {
  try {
    await sequelize.sync(options);
    logger.info('数据库模型同步成功');
    return true;
  } catch (error) {
    logger.error('数据库模型同步失败:', error);
    return false;
  }
};

export {
  sequelize,
  Sequelize,
  testConnection,
  syncModels
};

export const dbConfiguration = dbConfig;
